package com.cedifie.lendapp.ui.steps.act

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.cedifie.lendapp.MyApplication
import com.cedifie.lendapp.databinding.ActCameraOcrBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.RestartAct
import com.cedifie.lendapp.ui.user.act.CedUserFeedbackAct
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.imagecovert.ImageConvert
import com.lib.base.utils.ImageUtil
import com.lib.base.utils.TitleBarUtil
import com.lib.base.utils.log.LogHelper
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/21 11:08
 * @Annotation：驾驶证、护照、身份证拍照
 */
class CedCameraOcrAct: RestartAct() {
    lateinit var binding: ActCameraOcrBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUsePath = ""

    companion object {
        //类型 ： PASSPORT、IDCARD、DRIVING
        private const val INTENT_KEY_TYPE = "ocrType"
        fun start(context: Context, ocrType: String?) {
            if (TextUtils.isEmpty(ocrType)) {
                return
            }
            val intent = Intent(context, CedCameraOcrAct::class.java)
            intent.putExtra(INTENT_KEY_TYPE, ocrType)
            context.startActivity(intent)
        }
    }

    override fun getCedRootView(): View {
        binding = ActCameraOcrBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCedView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.titleLayout.setPadding(0,TitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()
    }

    override fun initCedListener() {
        binding.imgBack.setOnClickListener {
            finish()
        }

        //客服
        binding.imgKefu.setOnClickListener {
            onIntent(CedUserFeedbackAct::class.java)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CUSTOMER,"OcrCamera Page")
        }

        //拍照
        binding.imgTakeCamera.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CAMERA_TAKE_PHOTO,"OcrCamera Page")
            takeFilePhoto()
        }

        //重拍
        binding.remakeLayout.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_UPLOAD_RETAKE,"OcrCamera Page")
            showTakeView()
        }

        //使用
        binding.usePhotoLayout.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_UPLOAD_USE_PHOTO,"OcrCamera Page")
//            CedOcrUploadAct.start(this,getCedOrcType(),imgUsePath)
            val intent = Intent(this, CedOcrUploadAct::class.java)
            intent.putExtra("ocrType", getCedOrcType())
            intent.putExtra("imgPath", imgUsePath)
            usePhotoResultLauncher.launch(intent)
        }
    }

    override fun initCedData() {
    }

    /**
     * 使用照片
     */
    private val usePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                LogHelper.e(">>>>>>onActivityResult: data = " + result.data)
                showTakeView()
            }
        }
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        showTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.carmeraView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开后置摄像头
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = MyApplication.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata()
            metadata.isReversedHorizontal = true
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val imgUri = outputFileResults.savedUri

                    LogHelper.e("take photo complete>>>>>>>${imgUri?.path}")
                    // 图片处理
                    ImageConvert.covert(context = this@CedCameraOcrAct, uri = imgUri) { localPath, bitmap ->
                        if (localPath != null){
                            imgUsePath = localPath
                            LogHelper.e("imageConvert success>>>>>>>$localPath")
                            ImageUtil.instance?.loadImageUrl(this@CedCameraOcrAct,binding.imgPreview,localPath)
                            showCompleteView()
                        }
                    }
                }
                override fun onError(exception: ImageCaptureException) {
                    LogHelper.e("take photo failed>>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showTakeView(){
        binding.maskView.setMaskColor(Color.parseColor("#80000000"))
        binding.imgPreview.visibility = View.GONE
        binding.imgTakeCamera.visibility = View.VISIBLE
        binding.remakeLayout.visibility = View.INVISIBLE
        binding.usePhotoLayout.visibility = View.INVISIBLE
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCompleteView(){
        binding.maskView.setMaskColor(Color.parseColor("#000000"))
        binding.imgPreview.visibility = View.VISIBLE
        binding.imgTakeCamera.visibility = View.INVISIBLE
        binding.remakeLayout.visibility = View.VISIBLE
        binding.usePhotoLayout.visibility = View.VISIBLE
    }

    /**
     * 获取Ocr类型
     */
    private fun getCedOrcType(): String? {
        return intent.extras?.getString(INTENT_KEY_TYPE)
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_OCR_CAMERA_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_OCR_CAMERA_END,"")
        if (::cameraExecutor.isInitialized){
            cameraExecutor.shutdown()
        }
    }
}